<template>
  <div class="upload">
    <el-upload
      :action="action"
      :show-file-list="false"
      :name="name"
      ref="upload"
      :data="uploadParams"
      :before-upload="beforeUpload"
      :on-success="upload"
      :on-error="uploadError"
      :headers="{'Brand':brand,UserId:userId,Authorization:token}"
    >
      <el-button class="base-btn" type="primary" icon="el-icon-upload">{{btnTextName}}</el-button>
    </el-upload>
  </div>
</template>
<script>
// import { messageTipParams } from '@/utils/params.js'
import {
  showFullScreenLoading,
  tryHideFullScreenLoading
} from '@/utils/loading'
export default {
  data () {
    return {
      loadinginstace: null,
      messageTipParams:[],
      userId: localStorage.getItem('userName'),
      token: localStorage.getItem('token'),
    }
  },
  props: {
    action: {
      type: String,
      default: '',
      required: true
    },
    name: {
      type: String,
      default: 'file'
    },
    uploadParams: {
      type: Object
    },
    btnTextName: {
      type: String,
      default: "导入"
    },
    isCheckParams: {
      type: Boolean,
      default: false
    },
    isAsync: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    beforeUpload (file) {
      //导入必填字段校验
      if (this.isCheckParams) {
        let flag = true
        for (var key in this.uploadParams) {
          if (this.uploadParams[key] === '' || this.uploadParams[key] === undefined) {
            this.$message.error(`请选择${this.messageTipParams[key]}`)
            flag = false
            tryHideFullScreenLoading()
            return flag
          }
        }
        if (!flag) {
          return flag
        }
      }
      //上传文件前的校验
      if (!this.common.uploadValidExcel(file)) {
        this.$message.error('您上传的文件类型不正确，请重新上传')
        this.$refs.upload.clearFiles()
        return false
      }
      if (!this.isAsync) showFullScreenLoading('正在导入')
    },
    upload (res, file, fileList) { //文件上传成功时的钩子
      let { Status } = res
      tryHideFullScreenLoading()
      if (Status == "true") {
        let info = this.isAsync == true ? '正在导入，请到上传下载--导入结果页面查看导入结果' : '上传成功'
        let message = this.$message({
          type: 'success',
          showClose: true,
          duration: 5000,
          dangerouslyUseHTMLString: true,
          message: `<span>${info}</span>`
        })

        message.$el.querySelector('span').onclick = () => {
          this.$router.push('/result')
        }
      } else {
        this.$message.error(res.Msg)
      }
      this.$emit('uploadSuccess', res);
    },
    uploadError (err) { //文件上传失败时的钩子
      this.$message.error('上传失败')
      tryHideFullScreenLoading()
    }
  }
}
</script>

<style lang='less'>
.upload {
  display: inline-block;
}
</style>